package com.jse.json;

/*
Public Domain.
*/

import java.io.Closeable;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.time.temporal.TemporalAccessor;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import com.jse.Casts;
import com.jse.Lang;
import com.jse.Times;
import com.jse.anno.Column;

/**
 * 
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public class JsonObject extends LinkedHashMap<String,Object> {

	private static final long serialVersionUID = 1L;
	/**
     *  Regular Expression Pattern that matches JSON Numbers. This is primarily used for
     *  output to guarantee that we are always writing valid JSON.
     */
    static final Pattern NUMBER_PATTERN = Pattern.compile("-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?");

    /**
     * The map where the JSONObject's properties are kept.
     */
//    private final Map<String, Object> map;

    /**
     * Construct an empty JSONObject.
     */
    public JsonObject() {super();}
    private boolean dtime;
    public JsonObject(boolean dtime) {super();this.dtime=dtime;}

    public JsonObject(JSONTokener x){
        this();
        char c;
        String key;
        if (x.nextClean() != '{') {
            throw new RuntimeException("A JSONObject text must begin with '{'"+x.toString());
        }
        for (;;) {
            char prev = x.getPrevious();
            c = x.nextClean();
            switch (c) {
            case 0:
                throw new RuntimeException("A JSONObject text must end with '}'"+x.toString());
            case '}':
                return;
            case '{':
            case '[':
                if(prev=='{') {
                    throw new RuntimeException("A JSON Object can not directly nest another JSON Object or JSON Array."+x.toString());
                }
                // fall through
            default:
                x.back();
                key = x.nextValue().toString();
            }

            // The key is followed by ':'.

            c = x.nextClean();
            if (c != ':') {
                throw new RuntimeException("Expected a ':' after a key"+x.toString());
            }

            // Use syntaxError(..) to include error location

            if (key != null) {
                // Check if key exists
                if (this.get(key) != null) {
                    // key already exists
                    throw new RuntimeException("Duplicate key \"" + key + "\""+x.toString());
                }
                // Only add value if non-null
                Object value = x.nextValue();
                if (value!=null) {
                    this.put(key, value);
                }
            }

            // Pairs are separated by ','.

            switch (x.nextClean()) {
            case ';':
            case ',':
                if (x.nextClean() == '}') {
                    return;
                }
                if (x.end()) {
                    throw new RuntimeException("A JSONObject text must end with '}'"+x.toString());
                }
                x.back();
                break;
            case '}':
                return;
            default:
                throw new RuntimeException("Expected a ',' or '}'"+x.toString());
            }
        }
    }

    
	public JsonObject(Map m) {super(m);}

    public JsonObject(Object bean) {
        this();
        this.populateMap(bean);
    }
    public JsonObject(Collection<?> c) {
        this();
        this.add("list", c);
    }
    
    private JsonObject(Object bean, Set<Object> objectsRecord) {
        this();
        this.populateMap(bean, objectsRecord);
    }

    public JsonObject(String source){
        this(new JSONTokener(source));
    }
    
    protected JsonObject(int initialCapacity){super(initialCapacity);}
    
    public JsonObject(ResultSet rs) {
		try {
			var md=rs.getMetaData();
			for(int i = 1; i <=md.getColumnCount(); i++) {
				if("DATETIME".equals(md.getColumnTypeName(i))) {
					put(md.getColumnLabel(i),Times.parse(rs.getTimestamp(i)));
				}else if("JSON".equals(md.getColumnTypeName(i))) {
					put(md.getColumnLabel(i),Json.parse(rs.getString(i)));
				}else {
					put(md.getColumnLabel(i),rs.getObject(i));
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public JsonObject(ResultSet rs,ResultSetMetaData md, String[] headers) throws SQLException {
		try {
			for (int i = 1; i <=headers.length; i++) {
				if("DATETIME".equals(md.getColumnTypeName(i))) {
					put(headers[i-1],Times.parse(rs.getObject(i)));
				}else if("JSON".equals(md.getColumnTypeName(i))) {
					put(headers[i-1],Json.parse(rs.getString(i)));
				}else {
					put(headers[i-1],rs.getObject(i));
				}
			}
		} catch (SQLException e) {
			throw e;
		}
	}
    
	public void putAll(Map m) {super.putAll(m);}

    /**
     * Accumulate values under a key. It is similar to the put method except
     * that if there is already an object stored under the key then a JSONArray
     * is stored under the key to hold all of the accumulated values. If there
     * is already a JSONArray, then the new value is appended to it. In
     * contrast, the put method replaces the previous value.
     *
     * If only one value is accumulated that is not a JSONArray, then the result
     * will be the same as using put. But if multiple values are accumulated,
     * then the result will be like append.
     *
     * @param key
     *            A key string.
     * @param value
     *            An object to be accumulated under the key.
     * @return this.
     * @throws RuntimeException
     *            If the value is non-finite number.
     * @throws NullPointerException
     *            If the key is <code>null</code>.
     */
    public JsonObject accumulate(String key, Object value) throws RuntimeException {
        Object object = this.get(key);
        if (object == null) {
            this.put(key,
                    value instanceof JsonArray ? new JsonArray().set(value)
                            : value);
        } else if (object instanceof JsonArray) {
            ((JsonArray) object).add(value);
        } else {
            this.put(key, new JsonArray().set(object).set(value));
        }
        return this;
    }

    /**
     * Append values to the array under a key. If the key does not exist in the
     * JSONObject, then the key is put in the JSONObject with its value being a
     * JSONArray containing the value parameter. If the key was already
     * associated with a JSONArray, then the value parameter is appended to it.
     *
     * @param key
     *            A key string.
     * @param value
     *            An object to be accumulated under the key.
     * @return this.
     * @throws RuntimeException
     *            If the value is non-finite number or if the current value associated with
     *             the key is not a JSONArray.
     * @throws NullPointerException
     *            If the key is <code>null</code>.
     */
    public JsonObject append(String key, Object value) throws RuntimeException {
        Object object = this.get(key);
        if (object == null) {
            this.put(key, new JsonArray().set(value));
        } else if (object instanceof JsonArray) {
            this.put(key, ((JsonArray) object).set(value));
        } else {
            throw wrongValueFormatException(key, "JSONArray", null, null);
        }
        return this;
    }

    /**
     * Produce a string from a double. The string "null" will be returned if the
     * number is not finite.
     *
     * @param d
     *            A double.
     * @return A String.
     */
    public static String doubleToString(double d) {
        if (Double.isInfinite(d) || Double.isNaN(d)) {
            return "null";
        }

// Shave off trailing zeros and decimal point, if possible.

        String string = Double.toString(d);
        if (string.indexOf('.') > 0 && string.indexOf('e') < 0
                && string.indexOf('E') < 0) {
            while (string.endsWith("0")) {
                string = string.substring(0, string.length() - 1);
            }
            if (string.endsWith(".")) {
                string = string.substring(0, string.length() - 1);
            }
        }
        return string;
    }

    /**
     * Increment a property of a JSONObject. If there is no such property,
     * create one with a value of 1 (Integer). If there is such a property, and if it is
     * an Integer, Long, Double, Float, BigInteger, or BigDecimal then add one to it.
     * No overflow bounds checking is performed, so callers should initialize the key
     * prior to this call with an appropriate type that can handle the maximum expected
     * value.
     *
     * @param key
     *            A key string.
     * @return this.
     * @throws RuntimeException
     *             If there is already a property with this name that is not an
     *             Integer, Long, Double, or Float.
     */
    public JsonObject increment(String key) throws RuntimeException {
        Object value = this.get(key);
        if (value == null) {
            this.put(key, 1);
        } else if (value instanceof Integer) {
            this.put(key, ((Integer) value).intValue() + 1);
        } else if (value instanceof Long) {
            this.put(key, ((Long) value).longValue() + 1L);
        } else if (value instanceof BigInteger) {
            this.put(key, ((BigInteger)value).add(BigInteger.ONE));
        } else if (value instanceof Float) {
            this.put(key, ((Float) value).floatValue() + 1.0f);
        } else if (value instanceof Double) {
            this.put(key, ((Double) value).doubleValue() + 1.0d);
        } else if (value instanceof BigDecimal) {
            this.put(key, ((BigDecimal)value).add(BigDecimal.ONE));
        } else {
            throw new RuntimeException("Unable to increment [" + quote(key) + "].");
        }
        return this;
    }

    public boolean isNull(String key) {return this.get(key)==null;}

    /**
     * Produce a string from a Number.
     *
     * @param number
     *            A Number
     * @return A String.
     * @throws RuntimeException
     *             If n is a non-finite number.
     */
    public static String numberToString(Number number) throws RuntimeException {
        if (number == null) {
            throw new RuntimeException("Null pointer");
        }

        // Shave off trailing zeros and decimal point, if possible.

        String string = number.toString();
        if (string.indexOf('.') > 0 && string.indexOf('e') < 0
                && string.indexOf('E') < 0) {
            while (string.endsWith("0")) {
                string = string.substring(0, string.length() - 1);
            }
            if (string.endsWith(".")) {
                string = string.substring(0, string.length() - 1);
            }
        }
        return string;
    }
    
    public JsonArray getJSONArray(String key) {return (JsonArray)this.get(key);}
    public JsonObject getJSONObject(String key) { return (JsonObject)this.get(key); }
    public Integer getInt(String key){ return this.getInt(key,null);}
    public Integer getInt(String key,Integer d) {var o=this.get(key);return o==null?d:Casts.toInt(o);}
    public Long getLong(String key){ return this.getLong(key,null);}
    public Long getLong(String key,Long d) {var o=this.get(key);return o==null?d:Casts.toLong(o);}
    public String getString(String key){return this.getString(key,null);}
    public String getString(String key,String d){var o=this.get(key);return o==null?d:o.toString();}
    public Boolean getBoolean(String key){ return getBoolean(key,null);}
    public Boolean getBoolean(String key,Boolean d) {var o=this.get(key);return o==null?d:Casts.toBoolean(o);}

    /**
     * Populates the internal map of the JSONObject with the bean properties. The
     * bean can not be recursive.
     *
     * @see JsonObject#JSONObject(Object)
     *
     * @param bean
     *            the bean
     */
    private void populateMap(Object bean) {
        populateMap(bean, Collections.newSetFromMap(new IdentityHashMap<Object, Boolean>()));
    }

    private void populateMap(Object bean, Set<Object> objectsRecord) {
        Class<?> klass = bean.getClass();
        boolean includeSuperClass = klass.getClassLoader() != null;
        Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods();
        for (final Method method : methods) {
            final int modifiers = method.getModifiers();
            if (Modifier.isPublic(modifiers)
                    && !Modifier.isStatic(modifiers)
                    && method.getParameterTypes().length == 0
                    && !method.isBridge()
                    && method.getReturnType() != Void.TYPE
                    && isValidMethodName(method.getName())) {
                final String key = getKeyNameFromMethod(method);
                if (key != null && !key.isEmpty()) {
                    try {
                    	method.setAccessible(true);
                        final Object result = method.invoke(bean);
                        if (result != null) {
                            if (objectsRecord.contains(result)) {
                                throw new RuntimeException("JavaBean object contains recursively defined member variable of key "+quote(key));
                            }
                            objectsRecord.add(result);
                            this.put(key, wrap(result, objectsRecord));
                            objectsRecord.remove(result);
                            if (result instanceof Closeable) {
                                try {
                                    ((Closeable) result).close();
                                } catch (IOException ignore) {
                                }
                            }
                        }
                    } catch (IllegalAccessException ignore) {
                    } catch (IllegalArgumentException ignore) {
                    } catch (InvocationTargetException ignore) {
                    }
                }
            }
        }
    }

    private static boolean isValidMethodName(String name) {
        return !"getClass".equals(name) && !"getDeclaringClass".equals(name);
    }

    private static String getKeyNameFromMethod(Method method) {
//        final int ignoreDepth = getAnnotationDepth(method, JsonIgnore.class);
//        if (ignoreDepth > 0) {
//            final int forcedNameDepth = getAnnotationDepth(method, JsonIgnore.class);
//            if (forcedNameDepth < 0 || ignoreDepth <= forcedNameDepth) {
//                return null;
//            }
//        }
        Column annotation = getAnnotation(method, Column.class);
        if (annotation != null && annotation.value() != null && !annotation.value().isEmpty()) {
            return annotation.value();
        }
        String key;
        final String name = method.getName();
        if (name.startsWith("get") && name.length() > 3) {
            key = name.substring(3);
        } else if (name.startsWith("is") && name.length() > 2) {
            key = name.substring(2);
        } else {
            return null;
        }
        // if the first letter in the key is not uppercase, then skip.
        // This is to maintain backwards compatibility before PR406
        // (https://github.com/stleary/JSON-java/pull/406/)
        if (key.length() == 0 || Character.isLowerCase(key.charAt(0))) {
            return null;
        }
        if (key.length() == 1) {
            key = key.toLowerCase(Locale.ROOT);
        } else if (!Character.isUpperCase(key.charAt(1))) {
            key = key.substring(0, 1).toLowerCase(Locale.ROOT) + key.substring(1);
        }
        return key;
    }

    /**
     * Searches the class hierarchy to see if the method or it's super
     * implementations and interfaces has the annotation.
     *
     * @param <A>
     *            type of the annotation
     *
     * @param m
     *            method to check
     * @param annotationClass
     *            annotation to look for
     * @return the {@link Annotation} if the annotation exists on the current method
     *         or one of its super class definitions
     */
    private static <A extends Annotation> A getAnnotation(final Method m, final Class<A> annotationClass) {
        // if we have invalid data the result is null
        if (m == null || annotationClass == null) {
            return null;
        }

        if (m.isAnnotationPresent(annotationClass)) {
            return m.getAnnotation(annotationClass);
        }

        // if we've already reached the Object class, return null;
        Class<?> c = m.getDeclaringClass();
        if (c.getSuperclass() == null) {
            return null;
        }

        // check directly implemented interfaces for the method being checked
        for (Class<?> i : c.getInterfaces()) {
            try {
                Method im = i.getMethod(m.getName(), m.getParameterTypes());
                return getAnnotation(im, annotationClass);
            } catch (final SecurityException ex) {
                continue;
            } catch (final NoSuchMethodException ex) {
                continue;
            }
        }

        try {
            return getAnnotation(
                    c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()),
                    annotationClass);
        } catch (final SecurityException ex) {
            return null;
        } catch (final NoSuchMethodException ex) {
            return null;
        }
    }
    
    public JsonObject put(String key, Collection<?> value){return put(key,Json.jsonArray(value));}
    public JsonObject put(String key,JsonArray value){return put(key,(Object)value);}
    public JsonObject put(String key,Map<?,?> value){return put(key,Json.jsonObject(value));}
    public JsonObject put(String key,JsonObject value){return put(key,(Object)value);}
    @Override public JsonObject put(String k,Object v){super.put(k, v);return this;}


    /**
     * Creates a JSONPointer using an initialization string and tries to
     * match it to an item within this JSONObject. For example, given a
     * JSONObject initialized with this document:
     * <pre>
     * {
     *     "a":{"b":"c"}
     * }
     * </pre>
     * and this JSONPointer string:
     * <pre>
     * "/a/b"
     * </pre>
     * Then this method will return the String "c".
     * A JSONPointerException may be thrown from code called by this method.
     *
     * @param jsonPointer string that can be used to create a JSONPointer
     * @return the item matched by the JSONPointer, otherwise null
     */
    public Object query(String jsonPointer) {
        return query(new JSONPointer(jsonPointer));
    }
    public Object query(JSONPointer jsonPointer) {
        return jsonPointer.queryFrom(this);
    }

    /**
     * Produce a string in double quotes with backslash sequences in all the
     * right places. A backslash will be inserted within &lt;/, producing
     * &lt;\/, allowing JSON text to be delivered in HTML. In JSON text, a
     * string cannot contain a control character or an unescaped quote or
     * backslash.
     *
     * @param string
     *            A String
     * @return A String correctly formatted for insertion in a JSON text.
     */
    @SuppressWarnings("resource")
    public static String quote(String string) {
        StringWriter sw = new StringWriter();
        synchronized (sw.getBuffer()) {
            try {
                return quote(string, sw).toString();
            } catch (IOException ignored) {
                // will never happen - we are writing to a string writer
                return "";
            }
        }
    }

    public static Writer quote(String string, Writer w) throws IOException {
        if (string == null || string.isEmpty()) {
            w.write("\"\"");
            return w;
        }

        char b;
        char c = 0;
        String hhhh;
        int i;
        int len = string.length();

        w.write('"');
        for (i = 0; i < len; i += 1) {
            b = c;
            c = string.charAt(i);
            switch (c) {
            case '\\':
            case '"':
                w.write('\\');
                w.write(c);
                break;
            case '/':
                if (b == '<') {
                    w.write('\\');
                }
                w.write(c);
                break;
            case '\b':
                w.write("\\b");
                break;
            case '\t':
                w.write("\\t");
                break;
            case '\n':
                w.write("\\n");
                break;
            case '\f':
                w.write("\\f");
                break;
            case '\r':
                w.write("\\r");
                break;
            default:
                if (c < ' ' || (c >= '\u0080' && c < '\u00a0')
                        || (c >= '\u2000' && c < '\u2100')) {
                    w.write("\\u");
                    hhhh = Integer.toHexString(c);
                    w.write("0000", 0, 4 - hhhh.length());
                    w.write(hhhh);
                } else {
                    w.write(c);
                }
            }
        }
        w.write('"');
        return w;
    }

    /**
     * Determine if two JSONObjects are similar.
     * They must contain the same set of names which must be associated with
     * similar values.
     *
     * @param other The other JSONObject
     * @return true if they are equal
     */
    public boolean similar(Object other) {
        try {
            if (!(other instanceof JsonObject)) {
                return false;
            }
            if (!this.keySet().equals(((JsonObject)other).keySet())) {
                return false;
            }
            for (final Entry<String,?> entry : this.entrySet()) {
                String name = entry.getKey();
                Object valueThis = entry.getValue();
                Object valueOther = ((JsonObject)other).get(name);
                if(valueThis == valueOther) {
                	continue;
                }
                if(valueThis == null) {
                	return false;
                }
                if (valueThis instanceof JsonObject) {
                    if (!((JsonObject)valueThis).similar(valueOther)) {
                        return false;
                    }
                } else if (valueThis instanceof JsonArray) {
                    if (!((JsonArray)valueThis).similar(valueOther)) {
                        return false;
                    }
                } else if (valueThis instanceof Number n1 && valueOther instanceof Number n2) {
                    if (n1.doubleValue()!=n2.doubleValue()) {
                    	return false;
                    }
                } else if (!valueThis.equals(valueOther)) {
                    return false;
                }
            }
            return true;
        } catch (Throwable exception) {
            return false;
        }
    }

    /**
     * Tests if the value should be tried as a decimal. It makes no test if there are actual digits.
     *
     * @param val value to test
     * @return true if the string is "-0" or if it contains '.', 'e', or 'E', false otherwise.
     */
    protected static boolean isDecimalNotation(final String val) {
        return val.indexOf('.') > -1 || val.indexOf('e') > -1
                || val.indexOf('E') > -1 || "-0".equals(val);
    }

    /**
     * Converts a string to a number using the narrowest possible type. Possible
     * returns for this function are BigDecimal, Double, BigInteger, Long, and Integer.
     * When a Double is returned, it should always be a valid Double and not NaN or +-infinity.
     *
     * @param val value to convert
     * @return Number representation of the value.
     * @throws NumberFormatException thrown if the value is not a valid number. A public
     *      caller should catch this and wrap it in a {@link RuntimeException} if applicable.
     */
    protected static Number stringToNumber(final String val) throws NumberFormatException {
        char initial = val.charAt(0);
        if ((initial >= '0' && initial <= '9') || initial == '-') {
            // decimal representation
            if (isDecimalNotation(val)) {
                // Use a BigDecimal all the time so we keep the original
                // representation. BigDecimal doesn't support -0.0, ensure we
                // keep that by forcing a decimal.
                try {
                    BigDecimal bd = new BigDecimal(val);
                    if(initial == '-' && BigDecimal.ZERO.compareTo(bd)==0) {
                        return Double.valueOf(-0.0);
                    }
                    return bd;
                } catch (NumberFormatException retryAsDouble) {
                    // this is to support "Hex Floats" like this: 0x1.0P-1074
                    try {
                        Double d = Double.valueOf(val);
                        if(d.isNaN() || d.isInfinite()) {
                            throw new NumberFormatException("val ["+val+"] is not a valid number.");
                        }
                        return d;
                    } catch (NumberFormatException ignore) {
                        throw new NumberFormatException("val ["+val+"] is not a valid number.");
                    }
                }
            }
            // block items like 00 01 etc. Java number parsers treat these as Octal.
            if(initial == '0' && val.length() > 1) {
                char at1 = val.charAt(1);
                if(at1 >= '0' && at1 <= '9') {
                    throw new NumberFormatException("val ["+val+"] is not a valid number.");
                }
            } else if (initial == '-' && val.length() > 2) {
                char at1 = val.charAt(1);
                char at2 = val.charAt(2);
                if(at1 == '0' && at2 >= '0' && at2 <= '9') {
                    throw new NumberFormatException("val ["+val+"] is not a valid number.");
                }
            }
            // integer representation.
            // This will narrow any values to the smallest reasonable Object representation
            // (Integer, Long, or BigInteger)

            // BigInteger down conversion: We use a similar bitLength compare as
            // BigInteger#intValueExact uses. Increases GC, but objects hold
            // only what they need. i.e. Less runtime overhead if the value is
            // long lived.
            BigInteger bi = new BigInteger(val);
            if(bi.bitLength() <= 31){
                return Integer.valueOf(bi.intValue());
            }
            if(bi.bitLength() <= 63){
                return Long.valueOf(bi.longValue());
            }
            return bi;
        }
        throw new NumberFormatException("val ["+val+"] is not a valid number.");
    }

    /**
     * Try to convert a string into a number, boolean, or null. If the string
     * can't be converted, return the string.
     *
     * @param string
     *            A String. can not be null.
     * @return A simple JSON value.
     * @throws NullPointerException
     *             Thrown if the string is null.
     */
    // Changes to this method must be copied to the corresponding method in
    // the XML class to keep full support for Android
    public static Object stringToValue(String string) {
        if ("".equals(string)) {
            return string;
        }
        if ("true".equalsIgnoreCase(string)) {
            return Boolean.TRUE;
        }
        if ("false".equalsIgnoreCase(string)) {
            return Boolean.FALSE;
        }
        if ("null".equalsIgnoreCase(string)) {
            return null;
        }
        char initial = string.charAt(0);
        if ((initial >= '0' && initial <= '9') || initial == '-') {
            try {
                return stringToNumber(string);
            } catch (Exception ignore) {
            }
        }
        return string;
    }

    /**
     * Make a JSON text of this JSONObject. For compactness, no whitespace is
     * added. If this would not result in a syntactically correct JSON text,
     * then null will be returned instead.
     * <p><b>
     * Warning: This method assumes that the data structure is acyclical.
     * </b>
     *
     * @return a printable, displayable, portable, transmittable representation
     *         of the object, beginning with <code>{</code>&nbsp;<small>(left
     *         brace)</small> and ending with <code>}</code>&nbsp;<small>(right
     *         brace)</small>.
     */
    @Override
    public String toString() {
        try {
            return this.toString(0);
        } catch (Exception e) {
        	e.printStackTrace();
            return null;
        }
    }

    /**
     * Make a pretty-printed JSON text of this JSONObject.
     *
     * <p>If <pre>{@code indentFactor > 0}</pre> and the {@link JsonObject}
     * has only one key, then the object will be output on a single line:
     * <pre>{@code {"key": 1}}</pre>
     *
     * <p>If an object has 2 or more keys, then it will be output across
     * multiple lines: <pre>{@code {
     *  "key1": 1,
     *  "key2": "value 2",
     *  "key3": 3
     * }}</pre>
     * <p><b>
     * Warning: This method assumes that the data structure is acyclical.
     * </b>
     *
     * @param indentFactor
     *            The number of spaces to add to each level of indentation.
     * @return a printable, displayable, portable, transmittable representation
     *         of the object, beginning with <code>{</code>&nbsp;<small>(left
     *         brace)</small> and ending with <code>}</code>&nbsp;<small>(right
     *         brace)</small>.
     * @throws RuntimeException
     *             If the object contains an invalid number.
     */
    @SuppressWarnings("resource")
    public String toString(int indentFactor) throws RuntimeException {
        StringWriter w = new StringWriter();
        synchronized (w.getBuffer()) {
            return this.write(w, indentFactor, 0).toString();
        }
    }

    /**
     * Make a JSON text of an Object value. If the object has an
     * value.toJSONString() method, then that method will be used to produce the
     * JSON text. The method is required to produce a strictly conforming text.
     * If the object does not contain a toJSONString method (which is the most
     * common case), then a text will be produced by other means. If the value
     * is an array or Collection, then a JSONArray will be made from it and its
     * toJSONString method will be called. If the value is a MAP, then a
     * JSONObject will be made from it and its toJSONString method will be
     * called. Otherwise, the value's toString method will be called, and the
     * result will be quoted.
     *
     * <p>
     * Warning: This method assumes that the data structure is acyclical.
     *
     * @param value
     *            The value to be serialized.
     * @return a printable, displayable, transmittable representation of the
     *         object, beginning with <code>{</code>&nbsp;<small>(left
     *         brace)</small> and ending with <code>}</code>&nbsp;<small>(right
     *         brace)</small>.
     * @throws RuntimeException
     *             If the value is or contains an invalid number.
     */
    public static String valueToString(Object value) throws RuntimeException {
    	// moves the implementation to JSONWriter as:
    	// 1. It makes more sense to be part of the writer class
    	// 2. For Android support this method is not available. By implementing it in the Writer
    	//    Android users can use the writer with the built in Android JSONObject implementation.
        return JSONWriter.valueToString(value);
    }

    /**
     * Wrap an object, if necessary. If the object is <code>null</code>, return the NULL
     * object. If it is an array or collection, wrap it in a JSONArray. If it is
     * a map, wrap it in a JSONObject. If it is a standard property (Double,
     * String, et al) then it is already wrapped. Otherwise, if it comes from
     * one of the java packages, turn it into a string. And if it doesn't, try
     * to wrap it in a JSONObject. If the wrapping fails, then null is returned.
     *
     * @param object
     *            The object to wrap
     * @return The wrapped value
     */
    public static Object wrap(Object object) {
        return wrap(object, null);
    }

    private static Object wrap(Object object, Set<Object> objectsRecord) {
        try {
            if (object ==null|| object instanceof JsonObject|| object instanceof JsonArray
                    || object instanceof Byte || object instanceof Character
                    || object instanceof Short || object instanceof Integer
                    || object instanceof Long || object instanceof Boolean
                    || object instanceof Float || object instanceof Double
                    || object instanceof String || object instanceof BigInteger
                    || object instanceof BigDecimal || object instanceof Enum) {
                return object;
            }

            if (object instanceof Collection c) {return Json.jsonArray(c);}
            
            if (object.getClass().isArray()) {
                return new JsonArray(object);
            }
            if (object instanceof Map m) {return Json.jsonObject(m);}
            Package objectPackage = object.getClass().getPackage();
            String objectPackageName = objectPackage != null ? objectPackage
                    .getName() : "";
            if (objectPackageName.startsWith("java.")
                    || objectPackageName.startsWith("javax.")
                    || object.getClass().getClassLoader() == null) {
                return object.toString();
            }
            if (objectsRecord != null) {
                return new JsonObject(object, objectsRecord);
            }
            return new JsonObject(object);
        }
        catch (RuntimeException exception) {
            throw exception;
        } catch (Exception exception) {
            return null;
        }
    }

    /**
     * Write the contents of the JSONObject as JSON text to a writer. For
     * compactness, no whitespace is added.
     * <p><b>
     * Warning: This method assumes that the data structure is acyclical.
     * </b>
     * @param writer the writer object
     * @return The writer.
     * @throws RuntimeException if a called function has an error
     */
    public Writer write(Writer writer) throws RuntimeException {
        return this.write(writer, 0, 0);
    }

    @SuppressWarnings("resource")
    static final Writer writeValue(Writer writer, Object value,
            int indentFactor, int indent,boolean dtime) throws RuntimeException, IOException {
        if (value == null || value.equals(null)) {
            writer.write("null");
        }else if (value instanceof Number) {
            // not all Numbers may match actual JSON Numbers. i.e. fractions or Imaginary
            final String numberAsString = numberToString((Number) value);
            if(NUMBER_PATTERN.matcher(numberAsString).matches()) {
                writer.write(numberAsString);
            } else {
                // The Number value is not a valid JSON number.
                // Instead we will quote it as a string
                quote(numberAsString, writer);
            }
        } else if (value instanceof Boolean) {
            writer.write(value.toString());
        } else if (value instanceof Enum<?>) {
            writer.write(quote(((Enum<?>)value).name()));
        } else if (value instanceof JsonObject jo) {
        	jo.write(writer, indentFactor, indent);
        } else if (value instanceof JsonArray ja) {
            ja.write(writer, indentFactor, indent);
        } else if (value instanceof Map map) {
        	if(map.getClass().getName().endsWith(".ScriptObjectMirror")&&map.toString().equals("[object Array]")) {
    			new JsonArray(map.values()).write(writer, indentFactor, indent);
        	}else new JsonObject(map).write(writer, indentFactor, indent);
        } else if (value instanceof Collection coll) {
            new JsonArray(coll).write(writer, indentFactor, indent);
        } else if (value.getClass().isArray()) {
            new JsonArray(value).write(writer, indentFactor, indent);
        } else if (value instanceof java.util.Date d) {
        	if(dtime) writer.write(d.getTime()+"");
        	else quote(Times.format(d), writer);
        } else if (value instanceof TemporalAccessor t) {
        	quote(Times.format(t), writer);
        } else {
            quote(value.toString(), writer);
        }
        return writer;
    }

    static final void indent(Writer writer, int indent) throws IOException {
        for (int i = 0; i < indent; i += 1) {
            writer.write(' ');
        }
    }

    /**
     * Write the contents of the JSONObject as JSON text to a writer.
     *
     * <p>If <pre>{@code indentFactor > 0}</pre> and the {@link JsonObject}
     * has only one key, then the object will be output on a single line:
     * <pre>{@code {"key": 1}}</pre>
     *
     * <p>If an object has 2 or more keys, then it will be output across
     * multiple lines: <pre>{@code {
     *  "key1": 1,
     *  "key2": "value 2",
     *  "key3": 3
     * }}</pre>
     * <p><b>
     * Warning: This method assumes that the data structure is acyclical.
     * </b>
     *
     * @param writer
     *            Writes the serialized JSON
     * @param indentFactor
     *            The number of spaces to add to each level of indentation.
     * @param indent
     *            The indentation of the top level.
     * @return The writer.
     * @throws RuntimeException if a called function has an error or a write error
     * occurs
     */
    public Writer write(Writer writer, int indentFactor, int indent)
            throws RuntimeException {
        try {
            boolean needsComma = false;
            final int length = this.size();
            writer.write('{');
            if (length == 1) {
            	final Entry<String,?> entry = this.entrySet().iterator().next();
                final String key = entry.getKey();
                writer.write(quote(key));
                writer.write(':');
                if (indentFactor > 0) {
                    writer.write(' ');
                }
                try{
                    writeValue(writer, entry.getValue(), indentFactor, indent,dtime);
                } catch (Exception e) {
                    throw new RuntimeException("Unable to write JSONObject value for key: " + key, e);
                }
            } else if (length != 0) {
                final int newIndent = indent + indentFactor;
                for (final Entry<String,?> entry : this.entrySet()) {
                    if (needsComma) {
                        writer.write(',');
                    }
                    if (indentFactor > 0) {
                        writer.write('\n');
                    }
                    indent(writer, newIndent);
                    final String key = entry.getKey();
                    writer.write(quote(key));
                    writer.write(':');
                    if (indentFactor > 0) {
                        writer.write(' ');
                    }
                    try {
                        writeValue(writer, entry.getValue(), indentFactor, newIndent,dtime);
                    } catch (Exception e) {
                        throw new RuntimeException("Unable to write JSONObject value for key: " + key, e);
                    }
                    needsComma = true;
                }
                if (indentFactor > 0) {
                    writer.write('\n');
                }
                indent(writer, indent);
            }
            writer.write('}');
            return writer;
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }

    /**
     * Create a new RuntimeException in a common format for incorrect conversions.
     * @param key name of the key
     * @param valueType the type of value being coerced to
     * @param cause optional cause of the coercion failure
     * @return RuntimeException that can be thrown.
     */
    private static RuntimeException wrongValueFormatException(
            String key,
            String valueType,
            Object value,
            Throwable cause) {
        if(value == null) {

            return new RuntimeException(
                    "JSONObject[" + quote(key) + "] is not a " + valueType + " (null)."
                    , cause);
        }
        // don't try to toString collections or known object types that could be large.
        if(value instanceof Map || value instanceof Iterable || value instanceof JsonObject) {
            return new RuntimeException(
                    "JSONObject[" + quote(key) + "] is not a " + valueType + " (" + value.getClass() + ")."
                    , cause);
        }
        return new RuntimeException(
                "JSONObject[" + quote(key) + "] is not a " + valueType + " (" + value.getClass() + " : " + value + ")."
                , cause);
    }

    /**
     * Create a new RuntimeException in a common format for recursive object definition.
     * @param key name of the key
     * @return RuntimeException that can be thrown.
     */
//    private static RuntimeException recursivelyDefinedObjectException(String key) {
//        return new RuntimeException(
//            "JavaBean object contains recursively defined member variable of key " + quote(key)
//        );
//    }
    
    public boolean containsPrifix(String prefix) {
    	return keySet().stream().anyMatch(k->k.startsWith(prefix));
    }
    
    public JsonObject prifix(String prefix) {
		try {
			JsonObject map = new JsonObject();
			forEach((k, v) -> {
				if (k.startsWith(prefix)) {
					map.put(k.replace(prefix, ""), v);
				}
			});
			return map;
		} catch (Exception e) {
			return null;
		}
	}

	public Map<String,String> smap() {
		var map=new HashMap<String,String>();
		forEach((k,v)->{map.put(k,v==null?"":v.toString());});
		return map;
	}
	public Map<String,String[]> smap2() {
		var map=new HashMap<String,String[]>();
		forEach((k,v)->{
			if(v==null) {
				map.put(k,null);
			}else if(v instanceof Collection||v.getClass().isArray()) {
				map.put(k,(String[])Casts.to(v,String[].class));
			}else 
			map.put(k,new String[]{v.toString()});
		});
		return map;
	}

	public <T> T get(String k,T d) {
		return (T)Objects.requireNonNullElse(get(k),d);
	}
	
	public JsonObject set(String k,Object v) {put(k,v); return this;}

	public JsonObject add(String k,Object v) {
		if(containsKey(k)){var o=get(k);
			if(o instanceof Collection c){c.add(v);return set(k,c);}
			else return set(k,new JsonArray().set(get(k)).set(v));
		}
		return set(k,v);
	}
	public <T> T toBean(Class<T> c) {return Lang.mapToBean(this, c);}

	public JsonObject loadProp(String prop) {
		Lang.properties(prop).forEach((k,v)->put(k.toString(),v));
		return this;
	}

	public String toXml() {return XML.toString(this);}
	//同reversed 类型不变
	public JsonObject asc() {
		return entrySet().stream()
			    .sorted(Map.Entry.<String,Object>comparingByKey())
			    .collect(Collectors.toMap(
			        Map.Entry::getKey,
			        Map.Entry::getValue,
			        (oldValue, newValue) -> oldValue,// 解决可能存在的键冲突问题，默认保留第一个值
			        () -> new JsonObject() // 提供一个新的TreeMap实例作为收集器，用于保持排序
		));
	}
	public JsonObject desc() {
		return entrySet().stream()
			    .sorted(Map.Entry.<String,Object>comparingByKey().reversed())
			    .collect(Collectors.toMap(
			        Map.Entry::getKey,
			        Map.Entry::getValue,
			        (oldValue, newValue) -> oldValue,// 解决可能存在的键冲突问题，默认保留第一个值
			        () -> new JsonObject() // 提供一个新的TreeMap实例作为收集器，用于保持排序
		));
	}
	
	/**
	 * 删除内部对象 不存在则返回默认值d
	 * @param k 键
	 * @param <T> d 默认值 (未获取到对象默认值不能空)
	 * @return 删除的对象,并转化为默认值的类型
	 */
	public <T> T remove(String k,T d) {
		Object o=remove(k);if(o==null)return d;
		return (T)Casts.to(o,d.getClass());
	}
	/**
	 * 删除内部对象并转化为String
	 * @param k 键
	 * @return 删除的对象,并转化为Strig类型
	 */
	public String removeStr(String k) {
		return Casts.toString(remove(k));
	}
	/**
	 * 删除内部对象并转化为Integer
	 * @param k 键
	 * @return 删除的对象,并转化为Integer类型
	 */
	public Integer removeInt(String k) {
		return Casts.toInt(remove(k));
	}
	/**
	 * 删除所有key,只保留匹配的第一个
	 * @param ks 所有key,可单个key或者字符串数组
	 * @return 匹配的第一个或null
	 */
	public Object removeString(String...ks) {
		Object o=null;
		for (int i = 0; i < ks.length; i++) {
			if(i==0)o=remove(ks[i]);
			if(o==null)o=remove(ks[i]);
			else remove(ks[i]);
		}
		return o;
	}
	
	/**
	 * 删除所有key,并保留匹配的第一个转化为T的类型
	 * @param d <T> 默认值,所有ks查找都为空则填充,本身不能为空
	 * @param ks 所有key,可单个key或者字符串数组
	 * @return
	 */
	public <T> T removeDef(T d,String...ks) {
		Object o=removeString(ks);if(o==null)return d;
		return (T)Casts.to(o,d.getClass());
	}
	
	
	
	public static void main(String[] args) {
		JsonObject jo=new JsonObject();
		jo.put("e", 1);
		jo.put("x", 1);
		jo.put("a", 1);
		jo.put("11", 1);
		jo.put("8", 1);
		TreeMap t=new TreeMap(jo);
		System.out.println(jo);
		System.out.println(jo.reversed());
		System.out.println(t);
		System.out.println(jo.asc());
		System.out.println(jo.desc());
	}
}
